/**
 * 请求封装
 */
import axios from "axios";
import { Toast } from "vant";
import router from './../router';
import storage from "./storage";
const TOKEN_INVALID = 'Token认证失败，请重新登录';
const NETWORK_ERROR = '网络请求异常、请稍后重试';
const systemType = '/area';

//  创建axios实例,添加全局配置
const service = axios.create({
  baseURL: 'http://118.31.62.187',
  // baseURL: '/api/',
  timeout: 8000
})

//  请求拦截
service.interceptors.request.use((req) => {
  //  TO-DO
  const headers = req.headers;
  const { token } = storage.getItem('userInfo') || '';
  if (!headers.Authorization) headers.Authorization = token;
  return req;
})

//  响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data;
  if (code === 200) {
    return data;
  } else if (code === 50001) {
    Toast.fail(TOKEN_INVALID);
    const currentPath = router.history.current.path;
    if (currentPath.indexOf('/login') === -1) {
      setTimeout(() => {
        router.push(`${systemType}/login`);
      }, 1500)
    }
    return Promise.reject(TOKEN_INVALID);
  } else {
    Toast.fail(msg || NETWORK_ERROR);
    return Promise.reject(msg || NETWORK_ERROR);
  }
})

function request(options) {
  options.method = options.method || 'get';
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
  }
  return service(options);
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options
    })
  }
});

export default request;
